<template>
  <div ref="chart"></div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { get_LibraryBorrow } from '../../../../api/api';

const props = defineProps({
  selectedStudentId: {
    type: Number,
    required: false,
    default: 1,
  },
});

// 监听 selectedStudentId 的变化并调用 fetchData
watch(() => props.selectedStudentId, (newValue) => {
  if (newValue) {
    fetchData(newValue); // 传递 newValue 到 fetchData
  }
});

// 获取 token
const getToken = () => {
  return localStorage.getItem('pz_token');
};

// 请求数据并更新状态
const fetchData = async (StudentID) => {
  try {
    const token = getToken();

    if (!token) {
      console.error('未找到 Token');
      return;
    }

    if (!StudentID) {
      console.error('无效的 StudentID:', StudentID);
      return;
    }

    // 设置请求头
    const headers = {
      'Authorization': `JWT ${token}`, // 将 token 作为 Bearer Token 传递
    };

    const response = await get_LibraryBorrow(StudentID, headers);

    const LibraryBorrow = response.data.data.data; // 这里获取实际的返回数据

    // console.log('LibraryBorrow:', LibraryBorrow);  // 打印 classData 的结构

    // 从 sourseNumberData 中提取学年和门数数据
    const borrow_count = LibraryBorrow.map(item => item.borrow_count);
    const major_avg_borrow_count = LibraryBorrow.map(item => item.major_avg_borrow_count);
    const year_month = LibraryBorrow.map(item => item.year_month);

    // 更新 ECharts 的配置
    option.xAxis[0].data = year_month;
    option.series[0].data = borrow_count;
    option.series[1].data = major_avg_borrow_count;

    const myChart = echarts.init(chart.value)
    myChart.setOption(option)
    window.addEventListener('resize', () => {
      myChart.resize()
    })
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

const chart = ref();
// 配置 ECharts 的选项
// const rateData = ['0'];
// for (let i = 1; i < alarmdata.length; i++) {
//   const diff = alarmdata[i] - alarmdata[i - 1];
//   const rate = diff / alarmdata[i - 1];
//   rateData.push(rate);
// }

const option = reactive({
  grid: {
    top: 25,
    right: 0,
    bottom: 10,
    left: 0,
    containLabel: true
  },
  legend: {
    data: [
      {
        name: '借阅数量'
      },
      {
        name: '专业平均借阅数量'
      }
    ],
    icon: 'rect',
    itemWidth: 13,
    itemHeight: 13,
    itemGap: 40,
    top: 0,
    right: 50,
    textStyle: {
      color: 'rgba(76, 155, 253, 1.0)'
    }
  },
  xAxis: [{
    data: ['大一上', '大一下', '大二上', '大二下', '大三上', '大三下'],
    axisLabel: {
      color: 'rgba(76, 155, 253, 1.0)',
      fontSize: 11
    },
    axisTick: {
      show: false
    },
    axisLine: {
      lineStyle: {
        color: 'rgba(0, 255, 0, 1.0)',
        width: 0
      }
    }
  }],
  yAxis: [
    {
      type: 'value',
      splitNumber: 10,
      axisLabel: {
        color: 'rgba(76, 155, 253, 1.0)'
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 0, 0.1)'
        }
      }
    }
  ],
  series: [
    {
      name: '借阅数量',
      type: 'bar',
      data: [0, 0, 0, 0, 0, 0],
      barMaxWidth: 15,
      itemStyle: {
        borderRadius: [20, 20, 0, 0],
        color: {
          type: 'linear',
          x: 0,
          y: -0.2,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: '#A7CEFF'
            },
            {
              offset: 1,
              color: '#5B8FF9'
            }
          ]
        }
      },
      emphasis: {
        label: {
          show: true,
          position: 'top',
          color: '#1890FF'
        }
      }
    },
    {
      name: '专业平均借阅数量',
      type: 'line',
      data: [0, 0, 0, 0, 0, 0],
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        color: '#FF8C09'
      },
      itemStyle: {
        color: '#FF8C09'
      },
      emphasis: {
        itemStyle: {
          borderWidth: 2,
          borderColor: '#fff'
        },
        label: {
          show: true,
          position: 'top',
          formatter: (params) => {
            const value = (params.value * 100).toFixed(2);
            return params.seriesName + ':' + value + '%';
          },
          color: '#FF8C09',
          align: 'left',
          offset: [10, 5]
        }
      }
    }
  ]
});
onMounted(() => {
  const myChart = echarts.init(chart.value)
  myChart.setOption(option)
  window.addEventListener('resize', () => {
    myChart.resize()
  })
})

</script>

<style lang="less" scoped></style>